package cn.fsd.service.impl;

import cn.fsd.domain.Commodity;
import cn.fsd.domain.Stock_in_out_record;
import cn.fsd.mapper.CommodityMapper;
import cn.fsd.mapper.Stock_in_out_recordMapper;
import cn.fsd.query.delivery.StockInOutQuery;
import cn.fsd.service.StockInOutService;
import cn.fsd.util.Constants;
import cn.fsd.vo.PageBean;
import cn.fsd.vo.StockInOutBean;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class StockInOutServiceImpl implements StockInOutService {

  @Autowired
  Stock_in_out_recordMapper stockInOutRecordMapper;
  @Autowired
  CommodityMapper commodityMapper;

  @Override
  public PageBean<Stock_in_out_record> getInOutRecordByPage(StockInOutQuery query) {
    PageBean<Stock_in_out_record> pageBean = new PageBean<>();


    // TODO 此处也需要修改为调用commodity的接口实现
    List<String> ids = commodityMapper.getCommodityIDsByName(query.getQuery());

    PageHelper.startPage(query.getPageNow(),query.getPageSize());

    List<Stock_in_out_record> result = stockInOutRecordMapper.getRecordByPage(query,ids);

    PageInfo<Stock_in_out_record> pageInfo = new PageInfo<>(result);

    pageInfo.setList(pageInfo.getList().stream().map(item -> {
      StockInOutBean bean = new StockInOutBean(item);
      // TODO 此处之后需要替换成使用openfeign调用deliveryService的commodity相关接口和storeroom的接口
      Commodity commodity = commodityMapper.selectByPrimaryKey(item.getCommodity_id());
      if (commodity != null) {
        bean.setCommodityName(commodity.getCommodity_name());
        bean.setCommodityCode(commodity.getCommodity_code());
        bean.setCommodityPrice(commodity.getOriginal_price());
      } else {
        bean.setCommodityName("未知商品");
        bean.setCommodityCode("------");
        bean.setCommodityPrice(0L);
      }
      bean.setInOutType(Constants.INOUTTYPES.get(item.getRecord_type()));
      return bean;
    }).collect(Collectors.toList()));

    pageBean.setRowData(pageInfo.getList());
    pageBean.setTotalRows(pageInfo.getTotal());
    pageBean.setTotalPages(pageInfo.getPages());

    return pageBean;
  }
}
